﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace zijian666.Data.SqlBuilders;
internal class OracleBuilder : TSqlBuilder
{
    public static readonly OracleBuilder Instance = new OracleBuilder();
    public override string PagingSql(string sql, long begin, int count)
    {
        return $"SELECT * FROM (SELECT ROWNUM AS RN, T.* FROM ({sql.TrimSemicolon()}) T WHERE ROWNUM <= {begin + count}) WHERE RN > {begin}";
    }


    private DbProviderFactory _dbProvider = default!;

    public override DbProviderFactory DbProvider
    {
        get
        {
            if (_dbProvider is null)
            {
                if (DbProviderFactories.TryGetFactory("Oracle.ManagedDataAccess.Client", out _dbProvider!))
                {
                    return _dbProvider;
                }
                if (DbProviderFactories.TryGetFactory("Oracle.DataAccess.Client", out _dbProvider!))
                {
                    return _dbProvider;
                }
                if (DbProviderFactories.TryGetFactory("System.Data.OracleClient", out _dbProvider!))
                {
                    return _dbProvider;
                }
                var name = DbProviderFactories.GetProviderInvariantNames().FirstOrDefault(x => x.Contains("Oracle", StringComparison.OrdinalIgnoreCase));
                if (name is null)
                {
                    throw new NotSupportedException("未找到 Oracle 提供程序");
                }
                _dbProvider = DbProviderFactories.GetFactory(name);
            }
            return _dbProvider;
        }
    }

    public override string GetParameterHolder(string parameterName)
    {
        return $":{parameterName}";
    }
}
